package com.bjpowernode.seckillweb.controller;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.entity.Users;
import com.bjpowernode.seckillweb.service.impl.LuaService;
import com.bjpowernode.vo.HttpResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Objects;

@RestController
public class SpikeController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private LuaService luaService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @PostMapping("/goods/{id}/{random}")
    public HttpResult doSpike(@PathVariable("id") Integer id, @PathVariable("random") String random, HttpServletRequest request) throws JsonProcessingException {
        Goods goods = (Goods) redisTemplate.opsForValue().get(Constants.REDIS_GOODS + id);
        if (!Objects.requireNonNull(goods).getRandomName().equals(random))
            return HttpResult.builder().code(Constants.ERROR).msg("不合法").build();
        HttpResult result = SeckillTimeValidator.validateSeckillTime(goods.getStartTime(), goods.getEndTime());
        if (result != null)
            return result;
        else {
            Users user = (Users) request.getSession().getAttribute(Constants.LOGIN_USER);
            Long luaResult = luaService.runLua(id, user.getId());
            if (luaResult == -1)
                return HttpResult.builder().code(Constants.ERROR).msg("您已秒杀过该商品，不能重复秒杀").build();
            if (luaResult == -2)
                return HttpResult.builder().code(Constants.ERROR).msg("服务器太拥挤，请稍后再试").build();
            if (luaResult == -3)
                return HttpResult.builder().code(Constants.ERROR).msg("商品售罄").build();
            Orders orders = Orders.builder()
                    .uid(user.getId())
                    .createTime(new Date())
                    .orderMoney(goods.getPrice())
                    .goodsId(goods.getId())
                    .buyNum(1)
                    .buyPrice(goods.getPrice())
                    .status(0)
                    .build();
            String orderStr = objectMapper.writeValueAsString(orders);
            Message message = MessageBuilder.withBody(orderStr.getBytes()).build();
            rabbitTemplate.convertAndSend(Constants.EXCHANGE_NAME_ORDER, Constants.ROUTING_KEY_ORDER, message);
            return HttpResult.builder().code(Constants.SUCCESS).msg("正在秒杀，请稍后查询结果").build();
        }
    }
}